/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.Iterator;
import java.util.Set;

/**
 * Cache工具类
 *
 * @author kongxiangsheng
 * @version 2013-5-29
 */
@Slf4j
public class CacheUtils {
    private static CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);
    /**
     * 获取缓存键名，多数据源下增加数据源名称前缀
     *
     * @param key
     * @return
     */
    protected static String getKey(String key) {
        return key;
    }

    /**
     * 获得一个Cache，没有则显示日志。
     *
     * @param cacheName
     * @return
     */
    protected static Cache<String, Object> getCache(String cacheName) {
        Cache<String, Object> cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new RuntimeException("当前系统中没有定义“" + cacheName + "”这个缓存。");
        }
        return cache;
    }


    /**
     * 从缓存中移除所有
     *
     * @param cacheName
     */
    protected static void removeAll(String cacheName) {
        Cache<String, Object> cache = getCache(cacheName);
        Set<String> keys = cache.keys();
        for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
            cache.remove(it.next());
        }
        log.info("清理缓存： {} => {}", cacheName, keys);
    }

}
